<?php
/**
 * site management object
 **/
class site
{
    
    public $db;
    public $table;
    public $data;
    public $validated;
    public $errors;

    function __construct()
    {
        global $db;
        $this->db = &$db;
        $this->table = DB_PRE.'sites';
    }

    /**
     * 添加站点数据
     * @author menghao
     * @param <array> $data
     * @return site
     */
    function set($data)
    {
        if($data['id'] == MASTER_ID)
        {
            $this->errors[] = '不允许对主站进行操作';
            return false;
        }
        if(!isset($data['withcore'])) //默认不同步核心代码
        {
            $data['withcore'] = 0;
        }
        if(isset($data['modules']) && is_array($data['modules']))
        {
            $data['modules'] = implode(',', $data['modules']);
        }
        else
        {
            $data['modules'] = '';
        }
        $data['ismaster'] = 0;
        $this->data = $data;
        return $this;
    }

    /**
     * 保存站点数据
     * @author menghao
     * @return <boolean>
     */
    function save($data = null)
    {
        if(isset($data))
        {
            $this->data = $data;
        }
        else
        {
            if(!isset($this->data))
            {
                throw new Exception('数据不存在'); 
            }
            if(!$this->validated)
            {
                throw new Exception('未经验证的数据'); 
            }
        }
        $orginal = $this->get_one($this->data['id']);
        if(empty($orginal))
        {
            $result = $this->db->insert($this->table, $this->data);
            $this->make_site_menu();
        }
        else
        {
            $result = $this->update();
        }
        //保存成功
        if($result)
        {
            $this->copy_code();
            $this->make_config();
            $this->make_module_menu();
        }
        else
        {
            return false;
        }
        return true;
    }

    function update()
    {
        return $this->db->simple_update($this->table, $this->data, array('id'=>$this->data['id']));
    }

    /**
     * 校验数据
     * @author menghao
     * @return <array> 校验结果
     */
    function validate()
    {
        if(!isset($this->data))
        {
            throw new Exception('不存在的数据');
        }
        if(!isset($this->data['sitename']) || empty($this->data['sitename']))
        {
            $this->errors['sitename'] = '站点名称不能为空！';
        }
        if(strlen($this->data['sitename'])>30)
        {
            $this->errors['sitename'] = '站点名称不能超过30个字节';
        }
        if(!isset($this->data['id']) || empty($this->data['id']))
        {
            $this->errors['id'] = '站点标识不能为空！';
        }
        if(strlen($this->data['id'])>20)
        {
            $this->errors['id'] = '站点标识不能超过20个字节';
        }
        if(!isset($this->data['url']) || empty($this->data['url']))
        {
            $this->errors['url'] = '访问地址不能为空！';
        }
        if(strlen($this->data['url']) > 50)
        {
            $this->errors['url'] = '访问地址不能超过50个字节';
        }
        
        $this->validated = true;
        return $this->errors;
    }

    /**
     * 获取站点数据
     * @author menghao
     * @param <string> $id
     * @return <array> 站点数据
     */
    function get_one($id)
    {
        $this->db->prepare("select * from $this->table where id=? and status=?");
        $this->db->set_string($id);
        $this->db->set_int(STATUS_NORMAL);
        $data = $this->db->execute(true);

        if(!empty($data))
        {
            $file = APP_ROOT . 'sites/' . $id . '/site.conf';
            $conf = new siteconf($file);
            $data['url'] = $conf->get('SITE_URL');
        }
        return $data;
    }

    /**
     * 查询所有站点信息
     * @author menghao
     * @return <array>
     */
    function all()
    {
        $this->db->prepare("select * from $this->table where status=? order by lasttime asc ");
        $this->db->set_int(STATUS_NORMAL);
        return $this->db->execute();
    }

    /**
     * 删除站点信息
     * @author menghao
     * @param <string> $id
     * @return <boolean>
     */
    function delete($id)
    {
        if(!isset($id) || empty($id))
        {
           throw new Exception('没有数据可以删除'); 
        }
        $result = $this->db->fake_delete($this->table, array('id' => $id));
        if($result)
        {
            $result = $this->flush_site_contents($id);
        }
        return $result;
    }

    /**
     * 将核心代码拷贝到站点目录 
     * @author menghao
     * return boolean
     */
    function copy_code()
    {
        $id = $this->data['id'];
        $site_info = $this->get_one($id);
        $modules = explode(',', $site_info['modules']);
        $site_dir = APP_ROOT . 'sites/' . $id . '/';

        //如果包含核心代码，拷贝之
        if($site_info['withcore'])
        {
            //目录
            $dirs = array('template','include','editor','css','js','cache');
            foreach($dirs as $dir)
            {
                copy_dirs(APP_ROOT.$dir, $site_dir.$dir);
            }
            //跟目录下的php文件
            $handle = opendir(APP_ROOT);
            while (false !== ($file = readdir($handle)))
            {
                //拷贝所有主站跟目录下的php文件
                if(substr($file, -4, 4) == '.php')
                {
                    copy(APP_ROOT.$file, $site_dir.$file);
                }
            }
//            copy_dirs(APP_ROOT.'upload', $site_dir);
        }
        //如果包含管理代码，拷贝之
        if ($site_info['withadmin']) 
        {
            copy_dirs(APP_ROOT.'admin', $site_dir.'admin');
        }
        //如果包含某模块代码，拷贝之
        if(!empty($modules))
        {
            foreach($modules as $m)
            {
                if(empty($m))
                {
                    continue;
                }
                copy_dirs(APP_ROOT.$m, $site_dir.$m);
            }
        }

        return true;
    }
    
    /**
     * 清空站点的相关数据
     *
     * @param string $siteid
     * @param array $tables
     * @return bool
     */
    function flush_site_contents($siteid, $tables=array('content','category','menu'))
    {
    	if(is_array($tables))
    	{
    		foreach ($tables as $table)
    		{
	    		$this->db->prepare('update '.DB_PRE.$table.' set status=? where siteid=?');
	    		$this->db->set_int(STATUS_DEL);
	    		$this->db->set_string($siteid);
	    		$this->db->execute();
    		}
    	}
    	return true;
    }
    
    /**
     * 检查站点是否为空
     *
     * @param string $siteid
     * @param array $tables
     * @return bool  true 为空  false为非空
     */
    function check_site_contents($siteid, $tables=array('content','category','menu'))
    {
    	if(is_array($tables))
    	{
    		foreach ($tables as $table)
    		{
	    		$this->db->prepare('select count(*) as nums from '.DB_PRE.$table.' where siteid=? and status=?');
	    		$this->db->set_string($siteid);
	    		$this->db->set_int(STATUS_NORMAL);
	    		$res = $this->db->execute(true);
	    		if($res['nums'] > 0)
	    		{
	    			return false;
	    		}
    		}
    	}
    	return true;
    }

    /**
     * 生成站点配置文件 
     * @author menghao
     * return boolean
     */
    function make_config()
    {
        $id = $this->data['id'];
        $site_conf = new siteconf(APP_ROOT . 'sites/'.$id . '/site.conf');
        $site_conf->set_site_conf('SITE_ID', $id);
        $site_conf->set_site_conf('IS_MASTER', $this->data['ismaster']);
        $site_conf->set_site_conf('SITE_URL', $this->data['url']);
        $site_conf->set_site_conf('SITE_NAME', $this->data['sitename']);
        return true;
    }

    /**
     * 生成站点菜单
     * @author menghao
     * return boolean
     */
    function make_site_menu()
    {
        include_once APP_ROOT . 'admin/include/menu.class.php';
        $menu = new menu();
        $menu->make_site_menu($this->data['id']);
        return true;
    }

    function make_module_menu()
    {
        include_once APP_ROOT . 'admin/include/menu.class.php';
        $menu = new menu();
        if(isset($this->data['modules']) && !empty($this->data['modules']))
        {
            $modules = explode(',', $this->data['modules']);
            $menu->add_site_module_menu($modules, $this->data['id']);
        }
    }

    /**
     * 生成站点缓存
     * @author menghao
     * return boolean
     */
    function make_cache()
    {
        include_once APP_ROOT . 'admin/include/cache_all.class.php';
        $id = $this->data['id'];
        $site_dir = APP_ROOT . 'sites/' . $id . '/';
        $cache = new cache_all;
        @dir_delete($site_dir.'cache');
        return copy_dirs(APP_ROOT.'cache', $site_dir.'cache');
    }

    function export($siteid)
    {
       $tables = $this->get_tables();
       $file = fopen('php://output', 'w+');
       $filename = $siteid.date('_Y_m_d',TIME).'.txt';
       header("Content-Disposition:attachment;filename=$filename");

       foreach($tables as $table)
       {
            $tablename = array_shift($table);
            $table_data = $this->get_site_data($siteid, $tablename);
            if(!empty($table_data) && is_array($table_data))
            {
                foreach($table_data as $r)
                {
                    fwrite($file, json_encode(array('table'=>$tablename,'data'=>$r))."\n");
                }
            }
       }
       fclose($file);
       return true;
    }

    function import()
    {
        require_once 'attachment.class.php';
        $attachment = new attachment();
		$aids = $attachment->upload('uploadfile');
        
        if(empty($aids))
        {
            throw new Exception($attachment->error());
        }
        $filename = APP_ROOT.$attachment->uploadedfiles[0]['filepath'];

        if(!file_exists($filename))
        {
            throw new Exception("文件：{$filename} 不存在");
        }
        $file = fopen($filename, 'r');
        while($line = fgets($file))
        {
            $data = json_decode($line, true);
            $tablename = $data['table'];
            $pri_key = $this->get_pri_key($tablename);
            $this->db->prepare("select * from $tablename where $pri_key=?");
            $this->db->set_string($data['data'][$pri_key]);
            $org_value = $this->db->execute(true);
            if(empty($org_value))
            {
                $this->db->insert($tablename, $data['data']);
            }
            else
            {
                if($org_value['status']==STATUS_DEL)
                {
                    continue;
                }
                $result = $this->db->simple_update($tablename, $data['data'], array($pri_key=>$data['data'][$pri_key]));
                if(!$result)
                {
                    print_r($data);
                    exit;
                }
            }
        }
        return true;
    }

    function get_pri_key($tablename)
    {
        $construct = $this->db->get_table_construct($tablename);
        return $construct['uuid'];
    }

    function get_site_data($siteid, $tablename)
    {
        $construct = $this->db->get_table_construct($tablename);
        // print_r($construct);
        if(!isset($construct['cols']['siteid']))
        {
            return true;
        }
        $this->db->prepare("select * from $tablename where siteid=? and status=?");
        $this->db->set_string($siteid);
        $this->db->set_int(STATUS_NORMAL);
        return $this->db->execute();
    }
    private function get_tables()
    {
        return $this->db->query("show tables");
    }
}
?>
